<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Circle extends Model
{
    protected $dateFormat = 'U';
    protected $table = "lexiang_circle";
    protected $primaryKey = 'circle_id';

    public function add($data)
    {
        $this_ = $this;
        if(isset($data['circle_id'])){
            $this_ = $this->where('circle_id',$data['circle_id'])->first();
        }
    	$this_->circle_name = $data['name'];
        $this_->circle_address = $data['address'] ?? '';
        $this_->lng = $data['lng'] ?? 0;
        $this_->lat = $data['lat'] ?? 0;
        $this_->city = $data['city'] ?? '';
        $this_->position = $data['position'] ?? '';
    	$this_->circle_range = $data['circle_range'] ?? 0;
    	if($this_->save()){
    		return [
    			'success'=>true,
    			'code'=>'000',
    			'message'=>'保存成功'
    		];
    	}else{
    		return [
    			'success'=>false,
    			'code'=>'006',
    			'message'=>'添加出错，请稍后再试！'
    		];
    	}
    }

    public function getShopSumAttribute($v)
    {
        return MealShop::where('circle_id',$this->circle_id)->count();
    }

    public function getUserSumAttribute($v)
    {
        return User::where('circle_id',$this->circle_id)->count();
    }

    public function getPtuserNumAttribute($v)
    {
        return User::where('circle_range_id',$this->circle_id)->count();
    }

    public function getCouponDistanceAttribute($v)
    {
        return get_distance($this->lat,$this->lng,$this->lat2,$this->lng2,true);
    }

    public function getCardNumAttribute($v)
    {
        return User::join('lexiang_meal_user_card','lexiang_meal_user_card.users_id','=','lexiang_user.user_id')
        ->where('lexiang_user.circle_range_id',$this->circle_id)
        ->where('lexiang_meal_user_card.card_invalid',1)
        ->count();
    }
}
